import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import main from '@/components/common/main'


Vue.use(Router)

let router = new Router({
  mode: 'history',
  routes: [{
    path: '/',
    name: 'index',
    component: main,
    children: [{
      path: '/',
      component: resolve => require(['../components/common/index.vue'], resolve)
    }, {
      path: '/page1',
      component: resolve => require(['../components/page/page1.vue'], resolve)
    }, {
      path: '/page2',
      component: resolve => require(['../components/page/page2.vue'], resolve)
    }, {
      path: '/page3',
      component: resolve => require(['../components/page/page3.vue'], resolve)
    }, {
      path: '/nav1/:id',
      props: true,
      component: resolve => require(['../components/page/page4.vue'], resolve)
    }, {
      path: '/nav2/:id',
      redirect: to => {
        const {
          hash,
          params,
          query
        } = to
        console.log(hash, ' -- ', params, ' -- ', query)
        return '/login'
      }
    }]
  }, {
    path: '/login',
    component: resolve => require(['../components/common/login.vue'], resolve)
  }, {
    path: '*',
    component: resolve => require(['../components/common/notFound.vue'], resolve)
  }]
})

//tab队列维护，并与左侧菜单同步
function maintenanceTabs(to){
  let flag = false
  const routers = store.state.selectedRouters
  for (let i = 0, len = routers.length; i < len; i++) {
    if (routers[i].route === to.path) { //该导航在tab列表中已存在
      flag = true
      store.commit('setCurrentActiveIndex', routers[i].index) //设置当前tab
      store.commit('setCurrentMenuItem', routers[i].route) //设置当前菜单选中项
      break
    }
  }
  if (!flag) { //该导航在tab列表中尚未存在
    const r = store.state.menuListMap[to.path]
    store.commit('addTab', r)
    store.commit('setCurrentActiveIndex', r.index)  //设置当前tab
    store.commit('setCurrentMenuItem', r.route) //设置当前菜单选中项
  }
}



router.beforeEach((to, from, next) => {
  maintenanceTabs(to) 
  
  console.log('router.beforeEach =>', JSON.stringify(to.path), ' -- > ', JSON.stringify(from.path))
  next()
})


export default router